package com.mjlf.framework.mydata;

import com.mjlf.framework.util.ConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @auther a123
 * @create 2018-08-31 19:48
 * @desc mysql 连接管理
 * 调用这个类 需要首先使用ConfigUtil读取配置信息
 */
public final class ConnectionManager {
    private static Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
    private final static Queue<Connection> CONNECTION_QUEUE;

    static {
        int max = 4;
        try{
            max = Integer.parseInt(ConfigUtil.getValue("mysql.connection.max").toString());
        }catch (Exception e){
            logger.error("mysql.connection.max 配置存在问题", e);
        }
        CONNECTION_QUEUE = new LinkedBlockingDeque<>(max);
    }

    public static void init() throws ClassNotFoundException, SQLException {
        int len = Integer.parseInt(ConfigUtil.getValue("mysql.connection.max").toString());
        for(int i = 0; i < len; i++){
            String driver = ConfigUtil.getValue("mysql.connection.driver").toString();
            String dbUrl = ConfigUtil.getValue("mysql.connection.dburl").toString();
            String user = ConfigUtil.getValue("mysql.connection.user").toString();
            String pass = ConfigUtil.getValue("mysql.connection.pass").toString();

            Class.forName(driver);
            Connection connection = DriverManager.getConnection(dbUrl,user, pass);

            CONNECTION_QUEUE.add(connection);
        }
    }

    /**
     * 获取mysql连接
     * @return
     */
    public static synchronized Connection getConnection(){

        if(CONNECTION_QUEUE.isEmpty()){
            if(ConfigUtil.getValue("mysql.connection.waiting") == null){
                try {
                    Thread.currentThread().sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    Thread.currentThread().sleep(Integer.parseInt((String) ConfigUtil.getValue("mysql.connection.waiting")));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return CONNECTION_QUEUE.poll();
    }

    public static void retriveConnection(Connection connection){
        CONNECTION_QUEUE.add(connection);
    }

    public void finalize(){
        Connection connection = null;
        while((connection = CONNECTION_QUEUE.poll()) != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
